package com.scheduled.demo.scheduled.config;

import com.scheduled.demo.scheduled.RedisScheduledAnnotationBeanPostProcessor;
import com.scheduled.demo.service.RedisDistributedLock;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Role;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TaskManagementConfigUtils;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 *
 * 定时任务配置类
 * @description:
 * @author: chenjianshuo
 * @create: 2019-08-26 14:13
 **/


public class SchedulerConfiguration implements SchedulingConfigurer {

    @Value("${scheduler.thread.count}")
    private int  schedulerThreadCount;

  

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        TaskScheduler taskScheduler = new ConcurrentTaskScheduler(scheduledExecutorService());
        taskRegistrar.setTaskScheduler(taskScheduler);
    }

    @Bean(destroyMethod="shutdown")
    public ScheduledExecutorService scheduledExecutorService() {
        return new ScheduledThreadPoolExecutor(schedulerThreadCount);
    }



    @Bean(name = TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME)
    @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    @Primary
    public ScheduledAnnotationBeanPostProcessor scheduledAnnotationProcessor(@Qualifier("redisDistributedLock") RedisDistributedLock redisDistributedLock) {
        return new RedisScheduledAnnotationBeanPostProcessor(redisDistributedLock);
    }


}
